//
//  BaseViewController.m
//  StarGroup
//
//  Created by APPYING on 14-6-20.
//  Copyright (c) 2014年 APPYING. All rights reserved.
//

#import "BaseViewController.h"
#import <CommonCrypto/CommonDigest.h>
#import <SystemConfiguration/SystemConfiguration.h>
#import "FilesOperation.h"


#define Kwidth self.view.frame.size.width
#define Kheight self.view.frame.size.height

//static AVObject *baseUserIdObject;// 如果用户已经登录，则将其avos类取下

@interface BaseViewController ()

@end

@implementation BaseViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
//状态栏字体变白
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.navigationController.navigationBar.alpha = 0.8;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.tabBarController.tabBar.frame = CGRectMake(0, kScreen_Height - 53, 320, 53);
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    version = [[[UIDevice currentDevice] systemVersion] floatValue];//判断当前系统的版本号
    connectionNetFlag = [self connectedToNetwork];
    
    // 唯一圈定用户的avos值
    NSUserDefaults *userIdDefaults = [NSUserDefaults standardUserDefaults];
    baseUserId = [userIdDefaults objectForKey:@"userId"];
    if (baseUserId == nil) {
        NSDictionary *dic = [[NSDictionary alloc] initWithContentsOfFile:[FilesOperation returnDocumentsFileAddress:@"userId.plist"]];
        baseUserId = [dic objectForKey:@"userId"];
    }
}

//+ (AVObject *)getUserIdObject {
//    if (baseUserIdObject == nil) {
//        NSUserDefaults *userIdDefaults = [NSUserDefaults standardUserDefaults];
//        NSString *userId = [userIdDefaults objectForKey:@"userId"];
//        if (userId == nil) {
//            NSDictionary *dic = [[NSDictionary alloc] initWithContentsOfFile:[FilesOperation returnDocumentsFileAddress:@"userId.plist"]];
//            userId = [dic objectForKey:@"userId"];
//        }
//        if (userId != nil) {
//            AVQuery *userIdQuery = [AVQuery queryWithClassName:@"UserId"];
//            baseUserIdObject = [userIdQuery getObjectWithId:userId];
//        }
//    }
//    return baseUserIdObject;
//}


- (NSString *)md5HexDigest:(NSString *)input {
    const char *original_str = [input UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(original_str, strlen(original_str), result);
    NSMutableString *hash = [NSMutableString string];
    for (int i = 0; i < 16; i++)
        [hash appendFormat:@"%02X", result[i]];
    return [hash lowercaseString];
}

- (NSString *)changeTheTime:(NSString *)inputTime
{
//    Tue Jul 08 11:30:02 +0800 2014
    //将“Fri Jun 27 11:49:04 +0800 2014"类型的时间转换成“2014-07-08”格式
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //模拟器正常，真机出错改正代码
    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    [dateFormatter setLocale:locale];
    [dateFormatter setDateFormat:@"EEE MMM dd HH:mm:ss zzz yyyy"];
    NSDate *date1 = [dateFormatter dateFromString: inputTime];
    
    dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *str = [dateFormatter stringFromDate:date1];
    return str;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(NSString *)dateChange:(NSString *)date
{
    //将“Fri 27 Jun 2014 11:49:04 "类型的时间转换成“2014-07-08 11:49:04”格式
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //模拟器正常，真机出错改正代码
    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    [dateFormatter setLocale:locale];
    [dateFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss"];
    NSDate *date1 = [dateFormatter dateFromString: date];
   
    dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    return [dateFormatter stringFromDate:date1];
}

- (CGSize)theWordSize:(NSString *)str andFont:(UIFont *)font andCGSize:(CGSize)sizeT {
    CGSize size;
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
        NSDictionary * tdic = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName,nil];
        size =[str boundingRectWithSize:sizeT options:NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingUsesFontLeading attributes:tdic context:nil].size;
    } else {
        size = [str sizeWithFont:font constrainedToSize:sizeT lineBreakMode:NSLineBreakByCharWrapping];//ios7以上已经摒弃的这个方法
    }
    return size;
}

- (BOOL)connectedToNetwork{
    //创建零地址，0.0.0.0的地址表示查询本机的网络连接状态
    struct sockaddr_storage zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.ss_len = sizeof(zeroAddress);
    zeroAddress.ss_family = AF_INET;
    // Recover reachability flags
    SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;
    //获得连接的标志
    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);
    //如果不能获取连接标志，则不能连接网络，直接返回
    if (!didRetrieveFlags)
    {
        return NO;
    }
    //根据获得的连接标志进行判断
    BOOL isReachable = flags & kSCNetworkFlagsReachable;
    BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
    return (isReachable&&!needsConnection) ? YES : NO;
}

- (void)showAlertView {
    disConnectionNet = [[UIAlertView alloc] initWithTitle:@"当前未连接网络" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil , nil];
    [disConnectionNet show];
}

- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        [HUD hide:YES];
    }
}

- (void)showHUDonTheViewWithWord:(NSString *)word andMarge:(int)margin andYoffSet:(int)YoffSet {

    if (HUD == nil) {
        HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    }
    HUD.mode = MBProgressHUDModeText;
    HUD.delegate = self;
    HUD.labelText = word;
    if (margin == 0) {
        HUD.margin = 20;
    } else {
        HUD.margin = margin;
    }
    if (YoffSet != 0) {
        HUD.yOffset = YoffSet;
    }
    HUD.removeFromSuperViewOnHide = YES;
}


- (void)showIndeterminateProgress {
    if (HUD == nil) {
       	HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
    }
    [self.navigationController.view addSubview:HUD];
    HUD.delegate = self;
    [HUD show:YES];
}

- (void)showIndeterminateProgress:(NSString *)word {
    if (HUD == nil) {
       	HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
    }
    [self.navigationController.view addSubview:HUD];
    HUD.delegate = self;
    HUD.labelText = word;
    [HUD show:YES];
}

- (void)showWithDetailsLabel:(NSString *)word andDetailWord:(NSString *)detailWord {
    if (HUD == nil) {
       	HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
    }
    [self.navigationController.view addSubview:HUD];
    HUD.delegate = self;
    HUD.labelText = word;
    HUD.detailsLabelText = detailWord;
    [HUD show:YES];
}

- (void)showWithCustomView:(NSString *)word {
    if (HUD == nil) {
       	HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
    }
    [self.navigationController.view addSubview:HUD];
    HUD.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"37x-Checkmark.png"]];
	
	// Set custom view mode
	HUD.mode = MBProgressHUDModeCustomView;
	
	HUD.delegate = self;
	HUD.labelText = word;
	
	[HUD show:YES];
	[HUD hide:YES afterDelay:3];
}

- (void)hudWasHidden:(MBProgressHUD *)hud {
    [HUD removeFromSuperview];
}

- (void)removeApplicationLibraryDirectoryWithDirectory:(NSString *)dirName {
    NSString *dir = [[[[NSSearchPathForDirectoriesInDomains(NSApplicationDirectory, NSUserDomainMask, YES) lastObject] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"Library"] stringByAppendingPathComponent:dirName];
    if ([[NSFileManager defaultManager] fileExistsAtPath:dir]) {
        [[NSFileManager defaultManager] removeItemAtPath:dir error:nil];
    }
}
-(void)alertViewShow:(NSString *)text {
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil
                                                message:text
            delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    
    [alert show];
}

- (void)setTabBarHidden:(BOOL)hidden {
    UIView *tab = self.tabBarController.view;
    
    if ([tab.subviews count] < 2) {
        return;
    }
    UIView *view;
    
    if ([[tab.subviews objectAtIndex:0] isKindOfClass:[UITabBar class]]) {
        view = [tab.subviews objectAtIndex:1];
    } else {
        view = [tab.subviews objectAtIndex:0];
    }
    
    if (hidden) {
        view.frame = tab.bounds;
    } else {
        view.frame = CGRectMake(tab.bounds.origin.x, tab.bounds.origin.y, tab.bounds.size.width, tab.bounds.size.height);
    }
    self.tabBarController.tabBar.hidden = hidden;
}

- (void)clearAllUIWebViewData {
    // Clear the webview cache...
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    //    [self removeApplicationLibraryDirectoryWithDirectory:@"Caches"];
    [self removeApplicationLibraryDirectoryWithDirectory:@"WebKit"];
    // Empty the cookie jar...
    for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
    }
    [self removeApplicationLibraryDirectoryWithDirectory:@"Cookies"];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
